package main

import (
	"encoding/json"
	"io/ioutil"
	"os"
	"path/filepath"
)

const defaultBasePackage = "com.ninelock.api."

const (
	configPath         = "config"
	dbConfigName       = "db_config.json"
	coderConfigName    = "coder_config.json"
	documentConfigName = "document_config.json"
	menuConfigName     = "menu_config.json"
)

var configFiles = [4]string{dbConfigName, coderConfigName, documentConfigName, menuConfigName}

type DBConfig struct {
	DBId       string `json:"db_id"`
	DBHost     string `json:"db_host"`
	DBName     string `json:"db_name"`
	DBUsername string `json:"db_username"`
	DBPassword string `json:"db_password"`
}

type CoderConfig struct {
	DBId        string `json:"db_id"`
	Tables      string `json:"tables"`
	BasePath    string `json:"base_path"`
	BasePackage string `json:"base_package"`
	Mode        int32  `json:"mode"`
}

type DocumentConfig struct {
	DBId     string `json:"db_id"`
	Tables   string `json:"tables"`
	FilePath string `json:"file_path"`
	Mode     int32  `json:"mode"`
}

var (
	dbConfigs       = make([]DBConfig, 0)
	coderConfigs    = make([]CoderConfig, 0)
	documentConfigs = make([]DocumentConfig, 0)
	menuConfigs     = make([]string, 0)
)

// 初始化配置文件
func init() {
	if !fileExists(configPath) {
		_ = os.MkdirAll(configPath, os.ModePerm)
	}
	for _, configFile := range configFiles {
		filePath := filepath.Join(configPath, configFile)
		if !fileExists(filePath) {
			_ = ioutil.WriteFile(filePath, []byte("[]"), os.ModePerm)
		}
	}
	for i := 0; i < len(configFiles); i++ {
		loadConfigs(i)
	}
}

// 读取配置文件
func loadConfigs(index int) {
	configBytes, _ := ioutil.ReadFile(filepath.Join(configPath, configFiles[index]))
	if len(configBytes) > 0 {
		switch index {
		case 0:
			_ = json.Unmarshal(configBytes, &dbConfigs)
		case 1:
			_ = json.Unmarshal(configBytes, &coderConfigs)
		case 2:
			_ = json.Unmarshal(configBytes, &documentConfigs)
		case 3:
			_ = json.Unmarshal(configBytes, &menuConfigs)
		default:
			break
		}
	}
}

// 保存配置文件
func reloadConfigs(index int) {
	var configBytes []byte
	switch index {
	case 0:
		configBytes, _ = json.Marshal(dbConfigs)
	case 1:
		configBytes, _ = json.Marshal(coderConfigs)
	case 2:
		configBytes, _ = json.Marshal(documentConfigs)
	case 3:
		configBytes, _ = json.Marshal(menuConfigs)
	default:
		break
	}
	_ = ioutil.WriteFile(filepath.Join(configPath, configFiles[index]), configBytes, os.ModePerm)
	loadConfigs(index)
}
